<template>
    <div class="category-detail-page">
        <el-card shadow="never">
            <el-form
                :model="form"
                label-position="right"
                label-suffix=":"
                label-width="150px"
                ref="form"
                :rules="rules">
                <el-form-item label="名称" prop="name">
                    <el-input
                        v-model="form.name"
                        placeholder="请输入学习主题名称"
                        class="input-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="主题描述" prop="context">
                    <el-input
                        v-model="form.context"
                        placeholder="请输入主题描述"
                        class="input-width"
                        type="textarea"
                        autosize
                    ></el-input>
                </el-form-item>
                <el-form-item label="学习内容和收获" prop="content">
                    <el-input
                        v-model="form.content"
                        placeholder="概述学习内容要点和潜在收获"
                        class="input-width"
                        type="textarea"
                        autosize
                    ></el-input>
                </el-form-item>
                <el-form-item label="选择学习阶梯属性" prop="category_id">
                    <el-select
                        v-model="form.category_id"
                        placeholder="为该学习主题选择一个学习阶梯或分类"
                        class="input-width">
                        <el-option
                            v-for="item in labelCategoryOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="关联一个学习路径">
                    <el-button type="primary" @click="getLabels">{{ "关联学习路径" }}</el-button>
                    <label-list
                        v-show="form.labels.length > 0"
                        :list="form.labels"
                        @delete="deleteLabel"></label-list>
                </el-form-item>
                <label-dialog
                ref="label"
                :list="form.label_ids"
                :companyId="companyId"
                @addLabel="addLabelHandle"></label-dialog>
            </el-form>
            <div class="text-center">
                <el-button :loading="posting" type="primary" @click="onSave">保 存</el-button>
            </div>
        </el-card>
    </div>
</template>

<script>
import LabelDialog from '../../components/dialog/LabelDialog';
import LabelList from '../../components/page/LabelList';

export default {
    components: {
        LabelDialog,
        LabelList,
    },
    data() {
        return {
            posting: false,
            form: {
                name: '',
                context: '',
                content: '',
                label_ids: [],
                category_id: '',
                labels: [],
                company_id: '',
            },
            id: this.$route.params.id,
            labelCategoryOptions: [],
            labelOptions: [],
            originLabels: [],
            companyId: '',
            listForm: {
                type: 2,
                companyId: '',
            },
            rules: {
                name: [
                    { required: true, message: '学习主题名称不能为空', trigger: 'blur' },
                ],
                context: [
                    { required: true, message: '主题描述不能为空', trigger: 'blur' },
                ],
                content: [
                    { required: true, message: '学习内容和收获不能为空', trigger: 'blur' },
                ],
                category_id: [
                    { required: true, message: '学习阶梯属性不能为空', trigger: 'blur' },
                ],
            },
        };
    },
    methods: {
        onSave() {
            this.$refs.form.validate(async (valid) => {
                if (!valid) return;
                this.posting = true;
                if (this.id) {
                    const res = await API.get(`course/bind/${this.id}`);
                    this.getDiffLabelIds(res);
                    API.put(`course/${this.id}`, this.form).then(() => {
                        this.posting = false;
                        // this.$router.push({name: 'CourseManage'});
                        this.$router.go(-1);
                    }).catch(err => {
                        $ele.$message.error(err.message);
                    }).finally(() => this.posting = false);
                } else {
                    this.getDiffLabelIds([]);
                    API.post('course', this.form).then(() => {
                        this.posting = false;
                        this.$router.push({name: 'CourseManage'});
                    }).catch(err => {
                        $ele.$message.error(err.message);
                    }).finally(() => this.posting = false);
                }
            });
        },
        fetchData() {
            if (this.id) {
                API.get(`course/${this.id}`).then((res) => {
                    for (const i of Object.keys(this.form)) {
                        if (res[i]) this.form[i] = res[i];
                    }
                    this.originLabels = res.label_ids;
                    this.companyId = res.company_id;
                    this.listForm.companyId = res.company_id;
                    API.get('category/list', {params: this.listForm}).then((data) => {
                        this.labelCategoryOptions = data;
                    });
                });
            }
        },
        fetchLabelCategory() {
            const courseCategoryType = 2;
            API.get(`category/list?type=${courseCategoryType}`).then((res) => {
                this.labelCategoryOptions = res;
            });
        },
        fetchLabel() {
            API.get('label/list').then((res) => {
                this.labelOptions = res;
            });
        },
        getDiffLabelIds(res) {
            this.form.add_label_ids = this.form.label_ids.filter(v => res.indexOf(v) === -1);
            this.form.del_label_ids = res.filter(v => this.form.label_ids.indexOf(v) === -1);
        },
        addLabelHandle(label) {
            if (!this.form.label_ids.includes(label.id)) {
                this.form.labels.push(label);
                this.form.label_ids = [];
                this.form.labels.map((el) => {
                    this.form.label_ids.push(el.id);
                    return el;
                });
            }
            $ele.$message.success('选择学习路径（岗位角色/学习计划/专题）成功');
        },
        getLabels() {
            this.$refs.label.open();
        },
        deleteLabel(index) {
            this.form.labels.splice(index, 1);
            this.form.label_ids = [];
            this.form.labels.map((el) => {
                this.form.label_ids.push(el.id);
                return el;
            });
        },
    },
    mounted() {
        this.fetchData();
    },
};
</script>

<style lang="scss">
.category-detail-page {
    .input-width {
        width: 300px;
    }
    .picture {
        width: 200px;
        height: 200px;
        line-height: 200px;
    }
    .uploader-icon {
        font-size: 20px;
        color: #8c939d;
        text-align: center;
    }
    .image-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
}
</style>
